package org.fall.mvc.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Configuration //当前类作为配置类
@EnableWebSecurity //启用Web环境下权限控制功能
@EnableGlobalMethodSecurity(prePostEnabled = true) //启用全局方法权限控制，并且设置prePostEnabled = true
public class WebAppSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;


    @Bean
    public BCryptPasswordEncoder getPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        //临时使用内存版登录的模式测试代码
//        auth.inMemoryAuthentication()
//                .withUser("tom")
//                .password("123123")
//                .roles("ADMIN");

        //正式功能中使用基于数据库的认证
        auth.userDetailsService(userDetailsService)
                .passwordEncoder(getPasswordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        // String数组，列出需要放行的资源的路径
        String[] permitUrls = {
                "/index.jsp",
                "/bootstrap/**",
                "/crowd/**",
                "/css/**",
                "/fonts/**",
                "/img/**",
                "/jquery/**",
                "/layer/**",
                "/script/**",
                "/ztree/**"};

        http.authorizeRequests() //对请求进行授权
                .antMatchers("/admin/to/login/page.html") //针对登录页进行设置
                .permitAll()   //无条件访问
                .antMatchers(permitUrls) //针对静态资源进行设置 传入的ant风格的url
                .permitAll()   //无条件访问
                .antMatchers("/admin/page/page.html") //针对分页显示Admin数据设定访问控制
//                .hasRole("经理")  //要求具备经理角色
                .access("hasRole('经理') or hasAuthority('user:get')")
                .anyRequest() // 设置其他未设置的全部请求
                .authenticated(); // 表示需要认证

        http.exceptionHandling().accessDeniedHandler(new AccessDeniedHandler() {
            @Override
            public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException {
                httpServletRequest.setAttribute("exception", new Exception("抱歉，您没有权限访问该资源"));
                httpServletRequest.getRequestDispatcher("/WEB-INF/system-error.jsp").forward(httpServletRequest, httpServletResponse);
            }
        });

        http.formLogin()//开启表单登录功能
                .loginPage("/admin/to/login/page.html") //指定登录页面
                .loginProcessingUrl("/security/do/login.html") //指定处理登录请求的地址
                .defaultSuccessUrl("/admin/to/main/page.html") //指定登录成功后前往的地址
                .usernameParameter("login-user") //账号的请求参数名称
                .passwordParameter("login-pwd") //密码的请求参数名称
                .and()
                .logout() //开启退出登录功能
                .logoutUrl("/security/do/logout.html") //指定退出登录地址
                .logoutSuccessUrl("/admin/to/login/page.html"); //指定退出成功以后前往的地址

        http.csrf()
                .disable();

    }
}
